import http from "http";
import config from "./config";
import querystring from "querystring";
import superagent from 'superagent';

export default function api(app) {
    app.use(async(ctx, next) => {

    	ctx.post = (url,request={},method='post')=>{
    		try{
				var {ticket=ctx.ticket,headerId,...other} = request;
				request = querystring.stringify(other);
				var headers = {
				      'Content-Type': 'application/x-www-form-urlencoded',
				      'Content-Length': Buffer.byteLength(request)
				    }
				if(headerId){
					headers.id = headerId;
				}
				if(ticket){
				 	headers.t = ticket;
				}
				var post_options = {
				    host: config("host",true),
				    port: config("port",true),
				    path: url,
				    method: method,
				    headers: headers
				  };
				 return new Promise( (resolve, reject)=>{
				 	var post_req = http.request(post_options, function (response) {
						var responseText=[];
						var size =0;
						response.on('data', function (data) {
						  responseText.push(data);
						  size+=data.length;
						});
						response.on('end',async function () {
							// if(pro){}
							if(process.env.NODE_ENV=='dev'){
								console.log("请求结果：",responseText.toString());
							}
							
							try{
								responseText = Buffer.concat(responseText,size);
								let result = JSON.parse(responseText.toString()||"{}");
								if(result.cd==102){
									ctx.clearSess();
									result.path = ctx.url||"/";
								}
						  		resolve(result);
							}catch(e){
								resolve(responseText||"");
							}
						});
						response.on('error',async function (e) {
							console.log("请求结果：eror ==",e);
							
						});
					});
					post_req.write(request);
					post_req.end();
				 })
			}catch(e){
				console.log(e,"===========")
			}
		}
		
		ctx.superagent = (method,url,data) => {
			let send = method == 'get'? 'query':'send';
			return new Promise((resolve, reject) => {
				try{
					superagent[method](url)[send](data).end((err,res) => {
						console.log("请求结果：",res.text)
						resolve(res.text);
					})
				}catch(e){
					console.log("发生错误：",e)
					reject(e);
				}
				
			})
			
		}
        await next();
    });
}



    
 
